import React, { useEffect } from 'react';
import { getMenuData } from '@ant-design/pro-layout';
import { useModel } from 'umi';
import * as H from 'history';
import { pick } from 'lodash';
import { globalStateType } from '../../models/useGlobalModel';
import useMediaQuery from 'use-media-antd-query';
import useHoxModel from './useEntryModel';

export default (props: {
  children: React.ReactNode;
  location: H.Location<H.LocationState>;
  route: any;
}): React.ReactNode => {
  const { children, location, route } = props;
  const { setGlobalState, cachedRoutes, clearGlobalState } = useModel('useGlobalModel');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { dispatch } = useHoxModel((model) => []);
  const windowSize = useMediaQuery();
  useEffect(() => {
    //左边导航只有在xxl，xl打开
    const leftNavCollapsed = ['xxl', 'xl'];
    if (!leftNavCollapsed.includes(windowSize)) {
      !initialState?.collapsed && setInitialState({ ...initialState, collapsed: true });
    } else {
      initialState?.collapsed && setInitialState({ ...initialState, collapsed: false });
    }
    dispatch({ windowSize });
  }, [windowSize]);

  useEffect(() => {
    //保存当前路由名称
    const { breadcrumb } = getMenuData(route.routes);
    const currentRoute: globalStateType['currentRoute'] = pick(
      breadcrumb[location.pathname] || {},
      ['path', 'name'],
    );
    //判断当前路由是不是页面元素
    if (Object.keys(currentRoute).length !== 0) {
      const hasPath = cachedRoutes.some((item: any) => {
        return location.pathname === item.path;
      });

      let newCachedRoutes = [...cachedRoutes];
      const isNotIndex = location.pathname !== '/entry/index';
      //首页的时候不添加
      isNotIndex && newCachedRoutes.push(currentRoute);

      const newCachedRoutesObject = isNotIndex && hasPath ? {} : { cachedRoutes: newCachedRoutes };

      setGlobalState({ currentRoute, ...newCachedRoutesObject });
    }
    return () => {
      //清理全局数据
      clearGlobalState();
    };
  }, [location.pathname]);

  return <>{children}</>;
};
